<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->
<template>
  <el-dialog v-model="options.visible" :title="t('updatePassword.title')" :close-on-click-modal="false" :close-on-press-escape="false" :append-to-body="true">
    <el-form :model="formData" :rules="formRules" ref="formRef" @keyup.enter="submitDataFormHandle()" label-width="120px">
      <el-form-item :label="t('updatePassword.username')">
        <span>{{ userStore.$state.name }}</span>
      </el-form-item>
      <el-form-item prop="password" :label="t('updatePassword.password')">
        <el-input v-model="formData.password" type="password" :placeholder="t('updatePassword.password')"></el-input>
      </el-form-item>
      <el-form-item prop="newPassword" :label="t('updatePassword.newPassword')">
        <el-input v-model="formData.newPassword" type="password" :placeholder="t('updatePassword.newPassword')"></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" :label="t('updatePassword.confirmPassword')">
        <el-input v-model="formData.confirmPassword" type="password" :placeholder="t('updatePassword.confirmPassword')"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="options.visible = false">{{ t('cancel') }}</el-button>
      <el-button type="primary" @click="submitDataFormHandle()">{{ t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import debounce from 'lodash/debounce';
import { reactive, nextTick, ref } from 'vue';
import { ElMessage, FormRules } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import type { ElForm } from 'element-plus';
import http from '@/utils/request';
import { clearLogin } from '@/utils';
import useUserStore from '@/stores/modules/user';
import { globalApi } from '@/api/global';

// #region 类型
interface FormData {
  password: string;
  newPassword: string;
  confirmPassword: string;
}
// #endregion

const { t } = useI18n();
const router = useRouter();
const userStore = useUserStore();
const formRef = ref<InstanceType<typeof ElForm> | null>(null);

// 表单数据
const formData = reactive<FormData>({
  password: '',
  newPassword: '',
  confirmPassword: '',
});
// 页面配置
const options = reactive({
  visible: false,
});
// #region 自定义规则‘
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (formData.newPassword !== value) {
    return callback(new Error(t('updatePassword.validate.confirmPassword')));
  }
  callback();
};
// #endregion
const formRules = reactive<FormRules<FormData>>({
  password: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  newPassword: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: t('validate.required'), trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' },
  ],
});

const init = async () => {
  options.visible = true;
  await nextTick();
  formRef.value?.resetFields();
};
// 表单提交
function submit() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      globalApi.password(formData).then((res) => {
        if (res.code === 0) {
          ElMessage.success(t('prompt.success'));
          options.visible = false;
          clearLogin();
          router.replace({ name: 'login' });
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
}
const submitDataFormHandle = debounce(submit, 1000, { leading: true, trailing: false });

defineExpose({
  init,
});
</script>
